<template>
    <van-nav-bar
        title="邮箱认证"
        left-text="返回"
        left-arrow
        @click-left="OnBack"
    />

    <van-form @submit="OnSubmit" label-align="right" colon>
        <van-field
            v-model="business.email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            readonly
            :rules="[
                { required: true, message: '请输入邮箱' },
                {
                    pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
                    message: '邮箱格式不正确',
                },
            ]"
        />

        <van-field
            v-model="code"
            name="code"
            center
            clearable
            label="验证码"
            placeholder="请输入验证码"
            :rules="[{ required: true, message: '请输入验证码' }]"
        >
            <template #button>
                <van-button
                    size="small"
                    type="primary"
                    @click="OnSend"
                    :disabled="disabled"
                    >{{ msg }}</van-button
                >
            </template>
        </van-field>

        <div style="width: 80%; margin: 2em auto">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>

<script setup>
const { proxy } = getCurrentInstance();

const business = proxy.$business;
const code = ref('');
const msg = ref('发送验证码');
const disabled = ref(false);

onBeforeMount(() =>
{
    if(business.value.auth == 1)
    {
        proxy.$success('您已认证成功了，无须重复认证',() => OnBack());
    }

    if(!business.value.email?.trim())
    {
        proxy.$success('您的邮箱不存在，请去基本资料添加邮箱地址',() => OnBack());
    }
})

// 邮箱发送
const OnSend = async () =>
{
    if(!business.value.email?.trim())
    {
        proxy.$fail('邮箱不能为空');

        return false;
    }

    msg.value = '正在发送中.....';

    const params = {
        busid:business.value.id,
        email:business.value.email
    }

    const result = await proxy.$http.post('/email/send',params);


    if(result.code === 1)
    {
        proxy.$success(result.msg);

        disabled.value = true;
        msg.value = 60;

        let T = setInterval(() => {
            if (msg.value <= 0) {
                //停止定时器
                clearInterval(T);
                msg.value = '重新发送验证码';
                disabled.value = false;
            } else {
                msg.value--;
            }
        }, 100);
    }else{
        proxy.$fail(result.msg);
    }
};

//邮箱验证
const OnSubmit = async (values) => {
    // 把当前用户的id追加到 values
    values.busid = business.value.id;

    const result = await proxy.$http.post('/email/check',values);

    if(result.code === 1)
    {
        proxy.$success(result.msg,() => OnBack());
    }else{
        proxy.$fail(result.msg);
    }
};

const OnBack = () => proxy.$router.back();
</script>
